using UniversalAdminSystem.Infrastructure.DependencyInject;
using UniversalAdminSystem.Infrastructure.Services;
using UniversalAdminSystem.Api.Middleware;
using Microsoft.OpenApi.Models;

var builder = WebApplication.CreateBuilder(args);

// 加载外部的允许文件配置，避免 appsettings.json 膨胀
builder.Configuration.AddJsonFile("AllowedFiles.json", optional: false, reloadOnChange: true);

builder.Services.AddHttpClient<SpaCyService>();
// 添加CORS服务
builder.Services.AddCors(options =>
{
    // 开发环境策略 - 允许所有来源
    options.AddPolicy("AllowAll", policy =>
    {
        policy.AllowAnyOrigin()
              .AllowAnyMethod()
              .AllowAnyHeader();
    });

    // 生产环境策略 - 指定允许的来源
    options.AddPolicy("AllowSpecific", policy =>
    {
        policy.WithOrigins(
                "http://localhost:5173",
                "http://localhost:3000",     // React开发服务器
                "http://localhost:8080",     // Vue开发服务器
                "http://localhost:4200",     // Angular开发服务器
                "https://mikuslittlenest.cn",     // 生产域名
                "http://www.mikuslittlenest.cn",
                "http://localhost:8081",
                "http://mikuslittlenest.cn"
              )
              .AllowAnyMethod()
              .AllowAnyHeader()
              .AllowCredentials();
    });
});

// Add services to the container.
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen(c =>
{
    c.SwaggerDoc("v1", new OpenApiInfo { Title = "Universal Admin System API", Version = "v1" });

    // 添加JWT认证配置
    c.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
    {
        Description = "JWT Authorization header using the Bearer scheme. Example: \"Authorization: Bearer {token}\"",
        Name = "Authorization",
        In = ParameterLocation.Header,
        Type = SecuritySchemeType.ApiKey,
        Scheme = "Bearer"
    });

    c.AddSecurityRequirement(new OpenApiSecurityRequirement
    {
        {
            new OpenApiSecurityScheme
            {
                Reference = new OpenApiReference
                {
                    Type = ReferenceType.SecurityScheme,
                    Id = "Bearer"
                }
            },
            new string[] {}
        }
    });
});

// 在应用启动时初始化权限规则配置
var configPath = Path.Combine(Directory.GetCurrentDirectory(), "PermissionRules.json");
var permissionRuleConfigService = new PermissionRuleConfigService(configPath);
permissionRuleConfigService.Initialize();

builder.Services.AddSingleton(permissionRuleConfigService);

// 显式注册 AllowedFilesConfig
builder.Services.Configure<UniversalAdminSystem.Infrastructure.Configs.AllowedFilesConfig>(
    builder.Configuration.GetSection("AllowedFiles"));

builder.Services.AddAllService(builder.Configuration);
builder.Services.AddControllers();

var app = builder.Build();

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}

app.UseCors("AllowSpecific");

// 添加JWT认证中间件
Console.WriteLine("正在注册JWT认证中间件...");
app.UseJwtAuthentication();
Console.WriteLine("JWT认证中间件注册完成");

app.MapControllers();
app.Run();
